package com.bims.jreport.utils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.itextpdf.kernel.colors.DeviceRgb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

/**
 * @author wangrenjie
 */
@Slf4j
public class ReportUtil {


    /**
     * 写入输出流
     *
     * @param response
     * @param outputStream
     */
    public static void writeOutputStream(HttpServletResponse response, ByteArrayOutputStream outputStream) {
        try {
            response.setCharacterEncoding(CharsetUtil.CHARSET_UTF_8.name());
            response.setContentType("application/pdf");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + IdUtil.fastSimpleUUID() + ".pdf");
            IoUtil.write(response.getOutputStream(), true, outputStream.toByteArray());
        } catch (IOException e) {
            log.error("write OutputStream  error is {}", e.getMessage());
        } finally {
            IoUtil.close(outputStream);
        }
    }

    /**
     * 截取RGB颜色的数组部分
     *
     * @param rgb
     * @return
     */
    public static int[] subRgb(String rgb) {
        return StrUtil.splitToInt(StrUtil.subBetween(rgb, "rgb(", ")"), StrUtil.COMMA);
    }


    public static DeviceRgb creatDeviceRgb(int[] rgb) {
        return new DeviceRgb(rgb[0], rgb[1], rgb[2]);
    }

    public static DeviceRgb creatDeviceRgb(String rgbStr) {
        int[] rgb = subRgb(rgbStr);
        return new DeviceRgb(rgb[0], rgb[1], rgb[2]);
    }
}
